package com.hghivln.controller.doctor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.hghivln.aspectj.annotation.Log;
import com.hghivln.aspectj.enums.BusinessType;
import com.hghivln.config.pay.PayService;
import com.hghivln.constants.Constants;
import com.hghivln.pojo.domain.CareOrder;
import com.hghivln.pojo.domain.CareOrderItem;
import com.hghivln.pojo.domain.OrderCharge;
import com.hghivln.pojo.domain.OrderChargeItem;
import com.hghivln.pojo.dto.OrderBackfeeDto;
import com.hghivln.pojo.dto.OrderBackfeeFormDto;
import com.hghivln.pojo.vo.AjaxResult;
import com.hghivln.pojo.vo.CareHistoryVo;
import com.hghivln.service.CareService;
import com.hghivln.service.OrderBackfeeService;
import com.hghivln.service.OrderChargeService;
import com.hghivln.utils.IdGeneratorSnowflake;
import com.hghivln.utils.ShiroUtils;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.math.BigDecimal;
import java.util.*;

/**
 * 退费
 */
@RestController
@RequestMapping("doctor/backfee")
public class OrderBackfeeController {

    @Reference
    private OrderChargeService orderChargeService;

    @Reference
    private CareService careService;

    @Reference
    private OrderBackfeeService orderBackfeeService;

    /**
     * 根据挂号ID查询已支付的处方信息及详情
     */
    @GetMapping("getChargedCareHistoryByRegId/{regId}")
    @HystrixCommand
    public AjaxResult getChargedCareHistoryByRegId(@PathVariable @Validated @NotBlank(message = "挂号单号不能为空") String regId) {
        CareHistoryVo careHistoryVo = careService.selectCareHistoryByRegId(regId);
        if (ObjectUtils.isEmpty(careHistoryVo)) {
            return AjaxResult.fail("【"+regId+"】的挂号单没有对应的病例信息，请核对后再查询");
        }
        List<CareOrder> careOrderList = careService.selectCareOrdersByChId(careHistoryVo.getChId());
        if (CollectionUtil.isEmpty(careOrderList)) {
            return AjaxResult.fail("【"+regId+"】的挂号单没相关的处方信息，请核对后再查询");
        }

        Map<String, Object> map = new HashMap<>();
        map.put("careHistory",careHistoryVo);
        map.put("careOrders", Collections.EMPTY_LIST);
        // 声明一个可以存放careOrders的集合
        List<Map<String,Object>> mapList=new ArrayList<>();

        for (CareOrder careOrder : careOrderList) {
            List<CareOrderItem> careOrderItems = careService.selectCareOrderItemByCoId(careOrder.getCoId(),Constants.ORDER_DETAILS_STATUS_1);
            if (CollectionUtil.isEmpty(careOrderItems)) {
                //如果当前处方已支付的详情为空 结束当前循环
                continue;
            } else {
                // 重新计算总价
                BigDecimal allAmount=new BigDecimal("0");
                for (CareOrderItem careOrderItem : careOrderItems) {
                    allAmount = allAmount.add(careOrderItem.getAmount());
                }
                Map<String, Object> careOrderMap = BeanUtil.beanToMap(careOrder);
                careOrderMap.put("careOrderItems",careOrderItems);
                careOrderMap.put("allAmount",allAmount);
                mapList.add(careOrderMap);
            }
        }
        if (CollectionUtil.isEmpty(mapList)) {
            return AjaxResult.fail("【"+regId+"】的挂号单没已支付的处方信息，请核对后再查询");
        } else {
            map.put("careOrders",mapList);
            return AjaxResult.success(map);
        }
    }

    /**
     * 创建现金退费订单
     */
    @PostMapping("createOrderBackfeeWithCash")
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")
    })
    @Log(title = "创建现金退费订单",businessType = BusinessType.INSERT)
    public AjaxResult createOrderBackfeeWithCash(@RequestBody @Validated OrderBackfeeFormDto orderBackfeeFormDto) {
        OrderBackfeeDto orderBackfeeDto = orderBackfeeFormDto.getOrderBackfeeDto();
        // 找到之前的收费订单
        String itemId = orderBackfeeFormDto.getOrderBackfeeItemDtoList().get(0).getItemId();
        OrderChargeItem orderChargeItem = orderChargeService.queryOrderChargeItemByItemId(itemId);
        // 根据订单ID查询主订单信息
        OrderCharge orderCharge = orderChargeService.queryOrderChargeByOrderId(orderChargeItem.getOrderId());
        if (ObjectUtils.isEmpty(orderCharge)) {
            return AjaxResult.fail("【"+orderBackfeeDto.getRegId()+"】的挂号单之前没有收费记录，不能使用现金退费，请核对后再查询");
        }
        // 生成退费单号
        String backId = IdGeneratorSnowflake.generatorIdWithProfix(Constants.ID_PROFIX_ODB);
        orderBackfeeDto.setBackId(backId);
        orderBackfeeDto.setSimpleUser(ShiroUtils.getCurrentSimpleUser());
        orderBackfeeDto.setBackType(Constants.PAY_TYPE_1);
        orderBackfeeDto.setOrderId(orderCharge.getOrderId());
        orderBackfeeService.saveOrderAndItems(orderBackfeeFormDto);
        // 因为是现金退费，所以直接更新详情状态
        orderBackfeeService.backSuccess(backId,null,Constants.PAY_TYPE_0);
        return AjaxResult.success("创建现在退费订单成功");
    }

    /**
     * 创建支付宝退费订单
     */
    @PostMapping("createOrderBackfeeWithZfb")
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")
    })
    @Log(title = "创建支付宝退费订单",businessType = BusinessType.INSERT)
    public AjaxResult createOrderBackfeeWithZfb(@RequestBody @Validated OrderBackfeeFormDto orderBackfeeFormDto) {
        OrderBackfeeDto orderBackfeeDto = orderBackfeeFormDto.getOrderBackfeeDto();
        // 找到之前的收费订单
        String itemId = orderBackfeeFormDto.getOrderBackfeeItemDtoList().get(0).getItemId();
        OrderChargeItem orderChargeItem = orderChargeService.queryOrderChargeItemByItemId(itemId);
        // 根据订单ID查询主订单信息
        OrderCharge orderCharge = orderChargeService.queryOrderChargeByOrderId(orderChargeItem.getOrderId());
        if (ObjectUtils.isEmpty(orderCharge)) {
            return AjaxResult.fail("【"+orderBackfeeDto.getRegId()+"】的挂号单之前没有收费记录，不能使用支付宝退费，请核对后再查询");
        }
        if (!orderCharge.getPayType().equals(Constants.PAY_TYPE_1)) {
            return AjaxResult.fail("【"+orderBackfeeDto.getRegId()+"】的挂号单之前的支付方式为现金，不能使用支付宝退费，请核对后再查询");
        }
        // 生成退费单号
        String backId = IdGeneratorSnowflake.generatorIdWithProfix(Constants.ID_PROFIX_ODB);
        orderBackfeeDto.setBackId(backId);
        orderBackfeeDto.setSimpleUser(ShiroUtils.getCurrentSimpleUser());
        orderBackfeeDto.setBackType(Constants.PAY_TYPE_1);
        orderBackfeeDto.setOrderId(orderCharge.getOrderId());
        orderBackfeeService.saveOrderAndItems(orderBackfeeFormDto);

        // 支付宝退费
        String outTradeNo = orderChargeItem.getOrderId();
        String tradeNo = orderCharge.getPayPlatformId();
        String refundAmount = orderCharge.getOrderAmount().toString();
        String refundReason = "买错了/不想买了";
        String outRequestNo=backId;
        Map<String, Object> map = PayService.payBack(outTradeNo, tradeNo, refundAmount, refundReason, outRequestNo);
        if (map.get("code").toString().equals("200")) {
            orderBackfeeService.backSuccess(backId,map.get("tradeNo").toString(),Constants.PAY_TYPE_1);
            return AjaxResult.success();
        } else {
            return AjaxResult.fail(map.get("msg").toString());
        }
    }

    /**
     * 分页查询所有退费订单
     */
    @GetMapping("queryAllOrderBackfeeForPage")
    @HystrixCommand
    public AjaxResult queryAllOrderBackfeeForPage(OrderBackfeeDto orderBackfeeDto) {
        return orderBackfeeService.queryAllOrderBackfeeForPage(orderBackfeeDto);
    }

    /**
     * 根据订单ID查询订单详情
     */
    @GetMapping("queryOrderBackfeeItemByBackId/{backId}")
    @HystrixCommand
    public AjaxResult queryOrderBackfeeItemByBackId(@PathVariable @Validated @NotBlank(message = "订单ID不能为空") String backId) {
        return orderBackfeeService.queryOrderBackfeeItemByBackId(backId);
    }
}
